package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.StringUtil;

/**
 * UpdateInfoServlet实现类
 */
@WebServlet("/UpdateInfoServlet")
public class UpdateInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserDao userDao = new UserDaoImpl();
    private UserService userService = new UserServiceImpl();

    public UpdateInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //修改密码
        String username = request.getParameter("username");
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        User user = userDao.login(username, oldPassword);
        String changePWDResult = "";
        if (user == null) {
            changePWDResult = "旧密码错误！";
        }

        if (StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)) {
            changePWDResult = "旧密码和新密码不能为空！";
        }

        if (StringUtil.isEmpty(changePWDResult)) {
            user.setPassword(newPassword);
            userService.saveUser(user);
            changePWDResult = "密码修改成功！";
        }

        request.setAttribute("changePasswordResult", changePWDResult);
        request.getRequestDispatcher("/updateInfo.jsp").forward(request, response);
        return;
    }

}